package forumSystem;

import java.util.HashMap;
import java.util.Vector;

import reactor.Reactor;

//import protocol.Notification;


public class ForumNotifier implements Runnable{

	private static HashMap<Integer, ForumNotifier> notifiers = new HashMap<Integer, ForumNotifier>();
	
	private int ForumID;
	int delayTimeMilis;
	Thread starter;
	boolean shouldRun = true;
	
	private ForumNotifier(int fid, int howOften)
	{
		ForumID = fid;		
		delayTimeMilis = 1000*60*howOften;
	}
	
	public static ForumNotifier InitNotifier(int fid, int howOften)
	{
		ForumNotifier fn = new ForumNotifier(fid, howOften);
		notifiers.put(fid, fn);
		return fn;
	}
	
	public static ForumNotifier get(int fid)
	{
		return notifiers.get(fid);
	}
	
	/*
	public ForumNotifier(int flag) {
		Forum f=Reactor.db.getForumByID(flag);
		int policyid=f.getPolictyID();
		ForumPolicy fp=Reactor.db.getPolicyByID(policyid);
		int ho=fp.getHowOften();
		this.ForumID=flag;
		this.delayTimeMilis=ho==1?0:(1000*60);
	}
	*/
	
	@Override
	public void run() 
	{
		Vector<Notification> toSend;
		System.out.println("ForumNotifier: " + ForumID + " should be running" );
		while(shouldRun)
		{
			try 
			{
				if(delayTimeMilis > 0)
					Thread.sleep(delayTimeMilis);
				else
				{
					synchronized (this) {
						this.wait();
					}
				}
				synchronized(ForumNotifications.class)
				{
					toSend = ForumNotifications.getNotifications(ForumID);
					ForumNotifications.removeBind(ForumID);
				}
				if(toSend != null)
				{
					for(int i=0; i<toSend.size(); i++)				
					{
						System.out.println(toSend.elementAt(i)+"%%%%%%%%%%%%%%%%");
						starter = new Thread(toSend.elementAt(i));
						starter.start();
					}
				}
				/*
				if(ForumSystemImpl.getForumById(ForumID) == null)
				{
					shouldRun = false;
					System.out.println("forum " + ForumID + " has been deleted.");
				}*/
			}
			catch (InterruptedException e)
			{
				//haha :) do nothing !!!
				System.out.println("WHY YOU NO RUN");
				e.printStackTrace();
			}
		}		
	}
	
	public void setDelayTime(int d)
	{
		delayTimeMilis = d;
	}
	
}
